﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.PublicOfficialSelectionService;
using System.Collections.ObjectModel;
using CommunitySystem.KaoHeService;
using CommunitySystem.EmpbasicService;
using EHR.Common;
using System.IO;
using System.Windows.Data;

namespace CommunitySystem.PageView
{
    public partial class BDGLControl : UserControl
    {

        private PublicOfficialSelectionServiceClient downLoadClient = new PublicOfficialSelectionServiceClient();
        private EmpbasicService.EmpBasicServiceClient Client = new EmpbasicService.EmpBasicServiceClient();
        public ObservableCollection<EmpbasicService.OrgForHRModel> OrgList =
            new ObservableCollection<EmpbasicService.OrgForHRModel>();
        ObservableCollection<EmpbasicService.OrgForHRModel> forumList = new ObservableCollection<EmpbasicService.OrgForHRModel>();
        private ShiTi1 shiti = new ShiTi1();
        public BDGLControl()
        {
            InitializeComponent();

            shiti.ygzt = "未导出";
            ygzt.DataContext = shiti;

            ListBoxOfLife.Items.Clear();
            Client.GetDengLuJueSeCompleted += new EventHandler<EmpbasicService.GetDengLuJueSeCompletedEventArgs>(Client_GetDengLuJueSeCompleted);
            Client.GetDengLuJueSeAsync(Session.LoginUser.LoginName);
            Client.GetOrgForHRModelCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelCompletedEventArgs>(Client_GetOrgForHRModelCompleted);
            Client.GetOrgForHRModelbyIDsCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs>(Client_GetOrgForHRModelbyIDsCompleted);
            Client.GetDengLuOrgCompleted+=new EventHandler<GetDengLuOrgCompletedEventArgs>(Client_GetDengLuOrgCompleted);

            Client.GetSYQMKHCompleted += new EventHandler<EmpbasicService.GetSYQMKHCompletedEventArgs>(Client_GetSYQMKHCompleted);
            Client.GetSYQMKHCountCompleted += new EventHandler<EmpbasicService.GetSYQMKHCountCompletedEventArgs>(Client_GetSYQMKHCountCompleted);

            Client.GetPersonnelInfoExcelCompleted += new EventHandler<GetPersonnelInfoExcelCompletedEventArgs>(Client_GetPersonnelInfoExcelCompleted);
        
        }
        private int pageSize = 20;
        void Client_GetSYQMKHCountCompleted(object sender, EmpbasicService.GetSYQMKHCountCompletedEventArgs e)
        {
            ObservableCollection<int> list = new ObservableCollection<int>();
            int last = e.Result % pageSize;
            int count = 0;
            if (last > 0)
                count = e.Result / pageSize + 1;
            else
                count = e.Result / pageSize;
            for (int i = 0; i < count; i++)
            {
                list.Add(i);
            }

            PagedCollectionView pcv = new PagedCollectionView(list);
            dataPager1.PageSize = 1;
            dataPager1.Source = null;
            dataPager1.Source = pcv;
        }

        void Client_GetSYQMKHCompleted(object sender, EmpbasicService.GetSYQMKHCompletedEventArgs e)
        {

            DGRole.ItemsSource = null;
            if (e.Result != null && e.Result.Count > 0)
                DGRole.ItemsSource = e.Result;
        }
       

    

        #region 获得组织机构树
        void Client_GetOrgForHRModelCompleted(object sender, EmpbasicService.GetOrgForHRModelCompletedEventArgs e)
        {
            OrgList = e.Result;
            forumList.Clear();
            foreach (EmpbasicService.OrgForHRModel i in e.Result)
            {
                forumList.Add(i);
            }
            AddTreeNode("全部单位", null);
        }

        private void AddTreeNode(string type, TreeViewItem treeViewItem)
        {
            List<EmpbasicService.OrgForHRModel> result = (from forumInfo in forumList
                                                          where forumInfo.Type == type
                                                          select forumInfo).ToList<EmpbasicService.OrgForHRModel>();

            if (result.Count > 0)
            {
                foreach (EmpbasicService.OrgForHRModel foruminfo in result)
                {
                    TreeViewItem objTreeNode = new TreeViewItem();

                    //StackPanel sp = new StackPanel();
                    CheckBox cb = new CheckBox();
                    cb.Content = foruminfo.Name;
                    cb.Tag = objTreeNode;
                    cb.DataContext = foruminfo;
                    //sp.Children.Add(cb);
                    cb.Click += new RoutedEventHandler(cb_Checked);
                    objTreeNode.Header = cb;
                    //objTreeNode.Header = foruminfo.Name;
                    //objTreeNode.DataContext = foruminfo;
                    //objTreeNode.Tag = foruminfo.ID;
                    if ((objTreeNode.Header as CheckBox).Content.ToString() == "组织机构") objTreeNode.IsExpanded = true;

                    //此样式将会添加的所有叶子结点上
                    //objTreeNode.ItemContainerStyle = this.Resources["RedItemStyle"] as Style;

                    //添加根节点
                    if (treeViewItem == null)
                    {
                        TreeOfLife.Items.Add(objTreeNode);
                    }
                    else
                    {
                        treeViewItem.Items.Add(objTreeNode);
                    }
                    AddTreeNode(foruminfo.Name, objTreeNode);
                }
            }
        }
        public int orgid { get; set; }
        public List<string> orgids = new List<string>();
        public string type { get; set; }
        void cb_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            EmpbasicService.OrgForHRModel rm = cb.DataContext as EmpbasicService.OrgForHRModel;
            if (cb.IsChecked == true)
            {
                //if (orgids != null)
                //{
                //orgid = Convert.ToInt32(((EmpbasicService.OrgForHRModel)cb.DataContext).ID);
                //tbTitle.Text = cb.Content.ToString();
                if (!orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                    orgids.Add(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
              
                CheckChildItem(cb.Tag as TreeViewItem);

                string ss = "";
                foreach (string i in orgids)
                    ss += i + ",";
                if (string.IsNullOrEmpty(ss) || orgids.Contains("79")) ss = "0";
                else ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
            }
            else
            {
                //if (orgids != null)
                //{
                if (orgids != null)
                {
                    if (orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Remove(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                }
            
                UnCheckChildItem(cb.Tag as TreeViewItem);

                string ss = "";
                foreach (string i in orgids)
                    ss += i + ",";
                if (ss.Length > 1) ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
            }
        }

        void CheckChildItem(TreeViewItem item)
        {
            foreach (TreeViewItem tvi in item.Items)
            {
                if (tvi != null)
                {
                    CheckBox cb = tvi.Header as CheckBox;
                    cb.IsChecked = true;
                    if (!orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Add(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                    CheckChildItem(tvi);
                }
            }
        }
        void UnCheckChildItem(TreeViewItem item)
        {
            foreach (TreeViewItem tvi in item.Items)
            {
                if (tvi != null)
                {
                    CheckBox cb = tvi.Header as CheckBox;
                    cb.IsChecked = false;
                    if (orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Remove(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                    UnCheckChildItem(tvi);
                }
            }
        }
        #endregion
        #region 左右拖动的条
        private GridLength _lastColLeftLength;
        private GridLength _lastColRightLength;
        private void GridSpliteTo_ToLeft(object sender, EventArgs e)
        {
            //已经到最左边，直接返回
            if (colLeft.Width.Value == 0.0)
            {
                return;
            }

            //
            if (colRight.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colLeft.Width = new GridLength(0);
                colRight.Width = new GridLength(150, GridUnitType.Star);
            }
        }

        private void GridSpliteTo_ToRight(object sender, EventArgs e)
        {
            if (colRight.Width.Value == 0)
            {
                return;
            }

            if (colLeft.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colRight.Width = new GridLength(0);
                colLeft.Width = new GridLength(300, GridUnitType.Star);
            }
        }
        #endregion
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            orgid = Convert.ToInt32(((OrgForHRModel)(ListBoxOfLife.SelectedItem)).ID);
            orgids.Clear();
            orgids.Add(orgid.ToString());
            LoadData(orgids[0]);
        }

     
        void Client_GetOrgForHRModelbyIDsCompleted(object sender, EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs e)
        {
            ListBoxOfLife.ItemsSource = e.Result;
            ListBoxOfLife.SelectedIndex = 0;
            orgid = Convert.ToInt32(e.Result[0].ID);
            orgids.Clear();
            orgids.Add(orgid.ToString());
            LoadData(orgids[0]);
        }

        void Client_GetDengLuJueSeCompleted(object sender, EmpbasicService.GetDengLuJueSeCompletedEventArgs e)
        {
            if (e.Result != "人事干部")
            {
                if (TreeOfLife.ItemsSource != null) TreeOfLife.ItemsSource = null;
                TreeOfLife.Visibility = System.Windows.Visibility.Visible;
                ListBoxOfLife.Visibility = System.Windows.Visibility.Collapsed;

   
                Client.GetOrgForHRModelAsync(0);
                OId = "";
                LoadData("");
            }
            else
            {
                TreeOfLife.Visibility = System.Windows.Visibility.Collapsed;
                ListBoxOfLife.Visibility = System.Windows.Visibility.Visible;

  
                Client.GetDengLuOrgAsync(Session.LoginUser.LoginName);
            }
        }
        public String[] Oldorgids;
        void Client_GetDengLuOrgCompleted(object sender, EmpbasicService.GetDengLuOrgCompletedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Result))
            {
                Oldorgids = e.Result.Split(',');
            }
            Client.GetOrgForHRModelbyIDsAsync("(" + e.Result + ")");
        }
       /// <summary>
        /// 编辑
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void NewData_Click(object sender, RoutedEventArgs e)
        {
            var seljw = this.DGRole.SelectedItem as Emp_BDGLModel;
           
            if (seljw != null)
            {
                BDGLWindow win = new BDGLWindow(seljw);
                win.Show();
                win.Closed+=new EventHandler(win_Closed);
            }
            else
                SilverlightMessageBoxLibrary.Message.InfoMessage("请选择一条信息进行编辑！");
        }

        void win_Closed(object sender, EventArgs e)
        {
            LoadData(OId);
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private Stream ExportPersonnelInfo = null;
        private void TG_Click(object sender, RoutedEventArgs e)
        {
            var seljw = this.DGRole.SelectedItem as Emp_BDGLModel;

            if (seljw != null)
            {
                if (string.IsNullOrEmpty(seljw.RMLY))
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("请先进行编辑，再导出审批表！");
                    return;
                }
                var downLoad = new SaveFileDialog()
                               {
                                   Filter = "Excel files(2003) (*.xls)|*.xls",
                               };
                if (downLoad.ShowDialog() == true)
                {
                    ExportPersonnelInfo = downLoad.OpenFile();

                    List<byte> content = new List<byte>();
                    string username = "干部任免审批表";
                    Client.GetPersonnelInfoExcelAsync(seljw.Id, username, content);
                }
            }
            else
                SilverlightMessageBoxLibrary.Message.InfoMessage("请选择一条信息进行导出！");
        }
        void Client_GetPersonnelInfoExcelCompleted(object sender, GetPersonnelInfoExcelCompletedEventArgs e)
        {
            Emp_BDGLModel selectedItem = this.DGRole.SelectedItem as Emp_BDGLModel;
            List<byte> content = e.UserState as List<byte>;
            CommunitySystem.EmpbasicService.FileTransferStream fff = e.Result;
            if (fff.IsFinished == false)
            {
                content.AddRange(fff.FileContent);
                string username = "干部任免审批表";
                Client.GetPersonnelInfoExcelAsync(selectedItem.Id, username, content);
            }
            else
            {
                content.AddRange(fff.FileContent);
                byte[] bytes = content.ToArray();
                ExportPersonnelInfo.Write(bytes, 0, bytes.Length);
                ExportPersonnelInfo.Close();
                ExportPersonnelInfo.Dispose();
                SilverlightMessageBoxLibrary.Message.InfoMessage("导出成功!");
                LoadData(OId);
            }
        }
        /// <summary>
        /// 空表下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TH_Click(object sender, RoutedEventArgs e)
        {
            var sfd = new SaveFileDialog()
            {
                Filter = "Excel files(2003) (*.xls)|*.xls"

            };
            if (sfd.ShowDialog() == true)
            {
                Stream s = sfd.OpenFile();
                Byte[] fileContent = Resource1.干部任免审批表;
                s.Write(fileContent, 0, fileContent.Length);
                s.Close();
            }
      

            SilverlightMessageBoxLibrary.Message.InfoMessage("下载完毕!");
        }
        private void ibtnQuery_Click(object sender, RoutedEventArgs e)
        {
            LoadData(OId);
        }
        private string OId { get; set; }
        public void LoadData(string orgids)
        {
            OId = orgids;
            string tj = QueryCon(orgids);

            Client.GetSYQMKHCountAsync(tj);
        }

        private string QueryCon(string orgids)
        {
            string tj = string.Empty;
            if (!string.IsNullOrEmpty(orgids))
                tj = string.Format(" and OrgID in ({0}) ", orgids);
            if (!string.IsNullOrEmpty(shiti.ygzt))
                tj += string.Format(" and BZ='{0}' ", shiti.ygzt);
        
            return tj;
        }

        void RMWindow_Closed(object sender, EventArgs e)
        {
            string ss = "";
            foreach (string ii in orgids)
                ss += ii + ",";
            if (string.IsNullOrEmpty(ss)) ss = "0";
            else ss = ss.Substring(0, ss.Length - 1);
            LoadData(ss);
        }

        private void dataPager1_PageIndexChanged(object sender, EventArgs e)
        {
            int index = dataPager1.PageIndex == -1 ? 0 : dataPager1.PageIndex;

            string tj = QueryCon(OId);
            Client.GetSYQMKHAsync(tj, index + 1, pageSize);
        }
    

    }
}
